package com.zuipin.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenjunjie
 * @remark 中文分词
 * @date 2017.8.25
 */
public class WordSearch {
	
	public static String wordSplit(String searchKey) {
		StringBuffer buffer = new StringBuffer();
		if (StringUtil.isBlank(searchKey)) {
			return "";
		}
		Map<String, Integer> keyMap = new HashMap<>();// 用于存储已加入筛选的词
		
		buffer.append(">\"").append(searchKey).append("\"");// 提高全词匹配的权重
		
		String symbol;// 权重符
		String regEx;
		
		symbol = ">"; // 提高按空格分词的权重
		regEx = " ";
		splitSearchKey(searchKey, buffer, keyMap, symbol, regEx);
		
		symbol = "";// 一般权重可以省略权重符
		regEx = RegexUtils.STR_SPECIAL;// 特殊符号分词
		splitSearchKey(searchKey, buffer, keyMap, symbol, regEx);
		
		symbol = "";
		regEx = RegexUtils.NOT_CHINESE;// 使用非中文正则,提取中文分词
		splitSearchKey(searchKey, buffer, keyMap, symbol, regEx);
		
		symbol = "";
		regEx = RegexUtils.ENGLISH_NUMBER_PROSKU;// 特殊符号+中文分词(匹配英文单词与商品编码)
		splitSearchKey(searchKey, buffer, keyMap, symbol, regEx);
		
		for (String key : keyMap.keySet()) {
			// System.out.printf("%s:%s\n", key, keyMap.get(key));
		}
		return buffer.toString();
	}
	
	/**
	 * @author chenjunjie
	 * @date 2017.8.25
	 * @param searchKey 查询输入值
	 * @param buffer 折分结果字符
	 * @param keyMap 已添加到筛选中的词
	 * @param symbol 查词权重符号
	 * @param regEx 分离符(正则)
	 * @remark 分离查询关键词
	 */
	private static void splitSearchKey(String searchKey, StringBuffer buffer, Map<String, Integer> keyMap, String symbol, String regEx) {
		String[] wordArr = searchKey.split(regEx);
		for (String word : wordArr) {
			if (StringUtil.isNotBlank(word)) {
				word = word.trim();
				if (keyMap.get(word) != null || word.trim().length() == 1) {
					// TODO 已加入筛选的词不再重复加入
					continue;
				}
				buffer.append(" ").append(symbol).append(word);
				keyMap.put(word, 1);
				// 下面是中文分词特殊处理,abcde两两拆分,抓拆成ab,bc,cd,de
				String sym = "<";// 不同权重
				splitChinese(buffer, keyMap, sym, word);
			}
		}
	}
	
	/**
	 * @param buffer
	 * @param keyMap
	 * @param symbol
	 * @param word
	 * @remark 中文两两分词
	 */
	private static void splitChinese(StringBuffer buffer, Map<String, Integer> keyMap, String symbol, String word) {
		
		// 如果分词是全中文,且长度大于2
		word = word.trim();
		int length = word.length();
		if (length > 2 && word.matches(RegexUtils.CHINESES)) {
			for (int i = 0; i < length; i++) {
				if (i == length - 1) {
					break;
				}
				String splitWord = word.substring(i, i + 2);
				if (keyMap.get(splitWord) != null) {
					// TODO 已加入筛选的词不再重复加入
					continue;
				}
				buffer.append(" ").append(symbol).append(splitWord);
				keyMap.put(splitWord, Convert.toInteger(keyMap.get(splitWord)) + 1);
			}
		}
	}
	
	public static void main(String[] args) {
		System.out.println(WordSearch.wordSplit("大益普洱茶 大益陈韵 2011年90g生茶 袋泡茶【金山团购】"));
	}
}
